<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p>
        exec() 方法用用于检索字符串中的正则表达式模式的匹配。
    </p>




    <script>
        let str = 'Hello world!';
        let pattern = /o/;
        let result = pattern.exec(str);
        console.log(result);
        //['o', index: 4, input: 'Hello world!', groups: undefined]
        //失败则返回 null
        console.log('------------------');


        //提取分组
        let str1 = '<div>{{Hello}}</div>';
        let pattern1 = /{{([a-zA-Z]+)}}/;
        let result1 = pattern1.exec(str1);
        console.log(result1);
        console.log('------------------');


        //替换replace()函数 
        let str2 = '<div>Hello {{world}}</div>';
        let pattern2 = /{{([a-zA-Z]+)}}/;
        let patternResult = pattern2.exec(str2);
        console.log(patternResult);
        str2 = str2.replace(patternResult[0], patternResult[1]);
        console.log(str2);
        console.log('------------------');

        //多次替换
        let str3 = '<div>Hello {{new}} {{world}}</div>';
        let pattern3 = /{{\s*([a-zA-Z]+)\s*}}/;
        let patternResult3 = pattern3.exec(str3);
        console.log(patternResult3);
        str3 = str3.replace(patternResult3[0], patternResult3[1]);
        console.log(str3);
        patternResult3 = pattern3.exec(str3);
        console.log(patternResult3);
        str3 = str3.replace(patternResult3[0], patternResult3[1]);
        console.log(str3);
        patternResult3 = pattern3.exec(str3);
        console.log(patternResult3);
        console.log('--------');


        //用循环来进行多次替换
        let str4 = '<div>Hello {{new}} {{world}}</div>';
        let pattern4 = /{{\s*([a-zA-Z]+)\s*}}/;
        let patternResult4 = null;
        while (patternResult4 = pattern4.exec(str4)) {
            str4 = str4.replace(patternResult4[0], patternResult4[1]);
        }
        console.log(str4);
        console.log('------------------');
    </script>
</body>

</html>